<template>
  <el-card>
    <!-- 查询 -->
    <el-form :model="queryParams" inline label-width="80px" class="search-form">
      <el-form-item label="项目名称">
        <el-select v-model="queryParams.itemName" clearable placeholder="请选择项目" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option v-for="v in allItemNameOpts" :key="v" :label="v" :value="v"/>
        </el-select>
      </el-form-item>

      <el-form-item label="科室">
        <el-select v-model="queryParams.roomName" clearable placeholder="请选择科室" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option v-for="item in roomListOpts" :key="item.id" :label="item.roomName" :value="item.roomName"/>
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option :value="1" label="空闲"/>
          <el-option :value="0" label="正在服务"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增项目</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格（无单位列） -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="itemName" label="项目名称"/>
      <el-table-column prop="itemCode" label="项目编码"/>
      <el-table-column prop="price" label="价格(元)"/>
      <el-table-column prop="roomName" label="所属科室"/>
      <el-table-column label="状态" width="90">
        <template #default="{row}">{{ row.status===1?'空闲':'正在服务' }}</template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
  </el-card>

  <!-- 新增/编辑弹窗（无单位） -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px">
    <el-form :model="form" ref="formRef" label-width="100px" :rules="formRules">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="项目名称" prop="itemName">
            <el-input v-model="form.itemName" placeholder="请输入项目名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目编码" prop="itemCode">
            <el-input v-model="form.itemCode" placeholder="请输入编码"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="价格(元)" prop="price">
            <el-input-number v-model="form.price" :min="0" :precision="2" style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属科室" prop="medicalRoomId">
            <el-select v-model="form.medicalRoomId" clearable placeholder="请选择科室" style="width:100%">
              <el-option v-for="item in roomListOpts" :key="item.id" :label="item.roomName" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width:100%">
              <el-option :value="1" label="空闲"/>
              <el-option :value="0" label="正在服务"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {ElMessage, ElMessageBox} from 'element-plus'
import {findExamItem, listExamItem, addExamItem, updateExamItem, delExamItem, roomList} from '../api/examItem.js'

export default {
  name: 'ExamItemView',
  data() {
    return {
      queryParams: {itemName: '', roomName: '', status: ''},
      pagination: {pageNum: 1, pageSize: 10, total: 0},
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      isAdd: true,
      form: {},
      allItemNameOpts: [],
      roomListOpts: [],
      formRules: {
        itemName: [{required: true, message: '请输入项目名称', trigger: 'blur'}],
        itemCode: [{required: true, message: '请输入项目编码', trigger: 'blur'}],
        price: [{required: true, message: '请输入价格', trigger: 'blur'}],
        medicalRoomId: [{required: true, message: '请选择科室', trigger: 'change'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}]
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadRoomList()
    this.loadAllSelectOptions()
  },
  methods: {
    async loadData() {
      const hasCondition = this.queryParams.itemName || this.queryParams.roomName || this.queryParams.status !== ''
      const api = hasCondition ? listExamItem : findExamItem
      const params = {...this.queryParams, pageNum: this.pagination.pageNum, pageSize: this.pagination.pageSize}
      const {data: res} = await api(params)
      if (res.code === 200) {
        this.tableData = res.obj?.list || []
        this.pagination.total = res.obj?.total || 0
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    },
    async loadAllSelectOptions() {
      const {data: res} = await findExamItem({pageNum: 1, pageSize: 10000})
      if (res.code === 200) {
        const list = res.obj?.list || []
        this.allItemNameOpts = [...new Set(list.map(i => i.itemName).filter(Boolean))].sort()
      }
    },
    async loadRoomList() {
      const {data: res} = await roomList()
      if (res.code === 200) this.roomListOpts = res.obj || []
    },
    handleQuery() {
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleReset() {
      this.queryParams = {itemName: '', roomName: '', status: ''}
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },
    handleAdd() {
      this.isAdd = true
      this.dialogTitle = '新增检查项目'
      this.form = {price: 0, status: 1}
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.isAdd = false
      this.dialogTitle = '编辑检查项目'
      this.form = {...row}
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        // ❌ 不再传 unit
        delete this.form.unit
        const api = this.isAdd ? addExamItem : updateExamItem
        const {data: res} = await api(this.form)
        if (res.code === 200) {
          ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
          this.dialogVisible = false
          this.loadData()
          this.loadAllSelectOptions()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      })
    },
    handleDel(row) {
      ElMessageBox.confirm('确认删除该项目？', '提示', {type: 'warning'})
          .then(async () => {
            const {data: res} = await delExamItem(row.id)
            if (res.code === 200) {
              ElMessage.success('删除成功')
              this.loadData()
              this.loadAllSelectOptions()
            } else {
              ElMessage.error(res.msg || '删除失败')
            }
          })
          .catch(() => {
          })
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}
</style>